$(function () {
    $("#jqGrid").jqGrid({
        url: '/platform/manage/lecture/list',
        datatype: "json",
        mtype: "get",
        colModel: [{
            label: 'Id',
            name: 'id',
            index: 'id',
            width: 50,
            hidden: true,
            key: true
        },
            {
                label: 'photo',
                name: 'photoUrl',
                index: 'photoUrl',
                width: 50,
                hidden: true
            }, {
                label: '姓名',
                name: 'name',
                index: 'name',
                width: 50,
            },
            {
                label: 'fileUrl',
                name: 'fileUrl',
                index: 'fileUrl',
                width: 50,
                hidden: true
            },
            {
                label: '证书编号',
                name: 'certificateNumber',
                index: 'certificateNumber',
                width: 100
            },
            {
                label: '身份证号',
                name: 'idCard',
                index: 'idCard',
                width: 100
            },
            {
                label: '所属公司',
                name: 'company',
                index: 'company',
                width: 100
            },
            {
                label: '级别',
                name: 'type',
                index: 'type',
                width: 50,
                formatter: function (value, options, row) {
                    if (value === 0) return "未填写";
                    if (value === 1) return "初级";
                    if (value === 2) return "中级";
                    if (value === 3) return "高级";
                    if (value === 4) return "专家";
                }
            },
            {
                label: '有效期',
                name: 'expiryDate',
                index: 'expiryDate',
                width: 100
            }
        ],
        viewrecords: true,
        height: 385,
        rowNum: 10,
        rowList: [10, 30, 50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth: true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader: {
            root: "result.list",
            page: "result.currPage",
            total: "result.totalPage",
            records: "result.totalCount"
        },
        prmNames: {
            page: "page",
            rows: "limit",
            order: "order"
        },
        loadComplete: function (data) {
            console.log("data", data);
        },
        gridComplete: function () {
            //隐藏grid底部滚动条
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({
                "overflow-x": "hidden"
            });
        }

    });
    layui.use('laydate', function () {
        var laydate = layui.laydate;
        //日期范围选择
        laydate.render({
            elem: '#date-range',
            format: 'yyyy-MM-dd',
            range: " - " //或 range: '~' 来自定义分割字符
        });
    });

    $("#photoImage").click(function () {
        $("#photo").click();
    });

    $("#photo").change(function () {
        var objUrl = getObjectURL(this.files[0]); //获取图片的路径，该路径不是图片在本地的路径
        if (objUrl != null) {
            $("#photoImage").attr("src", objUrl);
            vm.lecture.photoUrl = objUrl;
        }
    });

})

function getObjectURL(file) {
    var url = null;
    // 下面函数执行的效果是一样的，只是需要针对不同的浏览器执行不同的 js 函数而已
    if (window.createObjectURL != undefined) { // basic
        url = window.createObjectURL(file);
    } else if (window.URL != undefined) { // mozilla(firefox)
        url = window.URL.createObjectURL(file);
    } else if (window.webkitURL != undefined) { // webkit or chrome
        url = window.webkitURL.createObjectURL(file);
    }
    return url;
}

var vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        showAdd: false,
        showInfo: false,
        imageFile: null,
        searchData: {
            data: {
                list: []
            }
        },
        deletes: {
            id: 0,
            photoUrl: "",
            fileUrl: ""
        },
        title: "",
        options: [{
            text: '爱卡卡创业版初级讲师',
            value: 1
        },
            {
                text: '爱卡卡创业版中级讲师',
                value: 2
            },
            {
                text: '爱卡卡创业版高级讲师',
                value: 3
            },
            {
                text: '爱卡卡创业版专家级讲师',
                value: 4
            }
        ],
        lecture: {expiryDate: ''},
    },
    methods: {
        query: function () {
            var searchContent = $("#searchContent").val();
            if (searchContent == null || searchContent.length < 1) {
                vm.reload();
                return;
            }
            var urlStr = "/platform/manage/lecture/query?ct=" + searchContent;
            var index = layer.load(0, {
                shade: false
            }); //0代表加载的风格，支持0-2
            $.ajax({
                type: "get",
                url: urlStr,
                success: function (result) {
                    if (result.code == 200) {
                        vm.searchData.data.list[0] = result.result;
                        $("#jqGrid").jqGrid('clearGridData'); //清空表格
                        $("#jqGrid").jqGrid('setGridParam', { // 重新加载数据
                            datatype: 'local',
                            data: vm.searchData.data.list, //  newdata 是符合格式要求的需要重新加载的数据
                            page: 1
                        }).trigger("reloadGrid");
                        //						$("#jqGrid_ds")[0].addJSONData(myjsongrid);
                    } else {
                        layer.alert(result.message);
                    }
                    layer.close(index);
                },
                error: function (e) {
                    layer.close(index);
                    layer.alert("查询失败，请重试");
                },
                async: true
            });
        },
        update: function () {
            var id = getSelectedRow();
            this.title = "讲师信息";
            var rowid = $("#jqGrid").getGridParam("selrow");
            var rowData = $("#jqGrid").getRowData(rowid);
            vm.lecture = rowData;
            if (vm.lecture.type == '初级') {
                vm.lecture.type = 1;
            } else if (vm.lecture.type == '中级') {
                vm.lecture.type = 2;
            } else if (vm.lecture.type == '高级') {
                vm.lecture.type = 3;
            } else if (vm.lecture.type == '专家') {
                vm.lecture.type = 4;
            } else {
                vm.lecture.type = 0;
            }
            vm.showList = false;
            vm.showAdd = true;
        },
        add: function () {
            this.title = "新增讲师";
            this.showAdd = true;
            this.showList = false;
            this.showInfo = false;
            this.lecture = {id: null, expiryDate: ''};
        },
        saveOrUpdate: function () {
            var index = layer.load(0, {
                shade: false
            }); //0代表加载的风格，支持0-2
            var urlStr = (vm.lecture.id === null || vm.lecture.id === undefined) ? "/platform/manage/lecture/add" : "/platform/manage/lecture/update";
            vm.lecture.expiryDate = $("#date-range").val();
            if (vm.lecture.id === null || vm.lecture.id === undefined) {
                Vue.delete(vm.lecture, "id");
            }
            console.log(vm.lecture);
            $.ajaxFileUpload({
                url: urlStr,
                data: JSON.parse(JSON.stringify(vm.lecture)),
                type: "POST",
                contentType: "multipart/form-data",
                secureuri: false,
                fileElementId: 'photo',
                dataType: 'json',
                success: function (result) {
                    layer.close(index);
                    if (result.code == 200) {
                        vm.reload();
                        alert("操作成功");
                    } else {
                        alert(result.message);
                        if (vm.lecture.id == null) {
                            $("#photoImage").attr("src", "");
                        }
                    }
                },
                complete: function () {
                    $("#photo").replaceWith('<input type="file" style="display: none;" accept="image/*" name="photo" id="photo" class="form-control" placeholder="file" />');
                    $("#photo").change(function () {
                        var objUrl = getObjectURL(this.files[0]); //获取图片的路径，该路径不是图片在本地的路径
                        if (objUrl != null) {
                            $("#photoImage").attr("src", objUrl);
                            vm.lecture.photoUrl = objUrl;
                        }
                    });
                    layer.close(index);
                },
                error: function (e) {
                    layer.close(index);
                    console.log("error", e);
                    alert("请求失败，请重试");
                }
            });
        },
        del: function () {
            var rowid = $("#jqGrid").getGridParam("selrow");
            var rowData = $("#jqGrid").getRowData(rowid);
            var del = getSelectedRows();
            if (del.length == 0) {
                alert("请选择要删除的项");
                return;
            } else if (del.length > 1) {
                alert("不能批量删除");
                return;
            }
            vm.deletes.id = del[0];
            vm.deletes.fileUrl = rowData.fileUrl;
            vm.deletes.photoUrl = rowData.photoUrl;
            var index = layer.load(0, {
                shade: false
            }); //0代表加载的风格，支持0-2
            $.ajax({
                type: "post",
                url: "/platform/manage/lecture/del",
                dataType: "json",
                data: JSON.stringify(vm.deletes),
                success: function (result) {
                    layer.close(index);
                    if (result.code == 200) {
                        alert("操作成功");
                    } else {
                        alert(result.message);
                    }
                },
                complete: function () {
                    layer.close(index);
                    vm.reload();
                },
                error: function () {
                    layer.close(index);
                    alert("请求失败，请重试");
                },
                async: true
            });
        },
        reload: function () {
            vm.showAdd = false;
            vm.showList = true;
            vm.showInfo = false;
            this.lecture = {};
            $("#jqGrid").jqGrid('setGridParam', { // 重新加载数据
                url: '/platform/manage/lecture/list',
                datatype: "json",
                mtype: "get",
            }).trigger("reloadGrid");
        }
    }
});